<?php

namespace addons\xapply\controller;

use addons\xapply\Base;
use app\admin\model\xapply\App as AppModel;
use app\admin\model\xapply\Category;
use app\admin\model\xapply\Rule;

class App extends Base
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 检查更新
     * url: http://域名/addons/xapply/app/version
     * doc: http://lutui.net/doc/app/check-update.html
     */
    public function version()
    {
        $curr = $this->data['version']; // 当前版本
        return json(['url' => '']);
    }

    /**
     * 应用列表
     * url: http://域名/addons/xapply/app/list
     * doc: http://lutui.net/doc/app/app-list.html
     */
    public function list()
    {
        $list = Category::with(['apps' => function ($query){
            $query->where('status', 'normal');
            $query->order('weigh', 'desc');
            $query->with('rules');
        }])->order('weigh', 'desc')->select();
        $data = [];
        foreach ($list as $value){
            $apps = [];
            if ($value['apps']){
                $user = $this->auth->getUserinfo();
                foreach ($value['apps'] as $app){
                    if (Rule::getPerm($user, $app)){
                        $apps[] = [
                            'name' => $app['name'],
                            'icon' => $app['icon'],
                            'url' => 'app://' . $app['app_name'],
                        ];
                    }
                }
            }
            if ($apps) {
                $data[] = [
                    'name' => $value->name,
                    'apps' => $apps,
                ];
            }
        }
        return json($data);
    }

    /**
     * 应用短ID
     * url: http://域名/addons/xapply/app/id
     * doc: http://lutui.net/doc/app/app-id.html
     */
    public function id()
    {
        $id = $this->data['id'];
        $one = AppModel::with('rules')->where('app_name', $id)->find();
        $user = $this->auth->getUserinfo();
        if ($one && Rule::getPerm($user, $one)){
            return json(['url' => $one['url']]);
        }
        return json(['url' => $this->request->domain().'/assets/addons/xapply/__UNI__5FDB086.wgt']);
    }
}